import yaml

from common.Database_Util.database_util import DatabaseUtil


# 在加载配置文件时使用SafeLoader并添加一个构造器来处理!config标记
class ConfigLoader(yaml.SafeLoader):
    pass

def config_constructor(loader, node):
    value = loader.construct_scalar(node)
    return value  # 返回标记的值

ConfigLoader.add_constructor('!config', config_constructor)  # 注册自定义标签处理器


# 加载config host yaml文件
def load_config_host(file_path):
    with open(file_path, 'rb') as file:
        load_config = yaml.load(file, Loader=ConfigLoader)
    return load_config


# # 加载测试用例数据 yaml
# def load_test_cases(file_path):
#     with open(file_path, 'rb') as file:
#         test_cases = yaml.safe_load(file.read().decode('utf-8'))
#     # 解析全局变量等操作
#     return test_cases['test_cases']

# 修改后的加载测试用例数据 yaml 函数
# def load_test_cases(file_path):
#     with open(file_path, 'rb') as file:
#         content = yaml.safe_load(file.read().decode('utf-8'))
#     # 检查是否存在Testsuit键，如果不存在则使用默认值
#     testsuit = content.get('Testsuit', '控制器默认测试用例')
#     test_cases = content.get('test_cases', [])
#     # 返回Testsuit信息和测试用例列表
#     return testsuit, test_cases


def load_test_cases(file_path):
    with open(file_path, 'rb') as file:
        content = yaml.safe_load(file.read().decode('utf-8'))

    # 获取数据库信息
    random_ids = DatabaseUtil.get_random_ids()

    # 检查是否存在 Testsuit 键，如果不存在则使用默认值
    testsuit = content.get('Testsuit', '默认接口测试用例')
    test_cases = content.get('test_cases', [])

    # 替换测试用例中的占位符 # 读取MySQL数据侧
    for test_case in test_cases:
        if 'params' in test_case:
            params = test_case['params']
            if 'dc_id' in params:
                params['dc_id'] = random_ids['dc_id']
            if 'devices' in params:
                devices = params['devices']
                for device in devices:
                    if 'temp_id' in device:
                        device['temp_id'] = random_ids['temp_id']

    # 返回Testsuit信息和测试用例列表
    return testsuit, test_cases
